package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author baiWT
 * @Description
 * @Date 2022/4/9 13:42
 **/
@Configuration
public class FeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //RequestContextHolder拿到刚进来的请求
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                System.out.println("拦截器线程："+Thread.currentThread().getId());
                HttpServletRequest request = attributes.getRequest();
                //同步请求数据，cookie
                String cookie = request.getHeader("Cookie");
                //给新请求同步老请求cookie
                requestTemplate.header("Cookie",cookie);
                System.out.println("feign远程调用之前先进行RequestInterceptor.apply");
            }
        };
    }
}
